﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnrar;

namespace ComicTool.Model
{
    public class RarCompressedComic : Comic
    {
        public RarCompressedComic(string name, LoadingStrategy strategy)
            : base(name, strategy)
        {
        }

        protected override void LoadFromStream(Stream stream)
        {
            List<Page> pages = new List<Page>();
            RarArchive archive = RarArchive.Open(stream, false);
            archive.Entries.Where(e => e.FilePath.EndsWith("comicinfo.xml",
                StringComparison.InvariantCultureIgnoreCase)).ForEach(entry =>
            {
                MemoryStream ms = new MemoryStream();
                entry.WriteTo(ms);
                ms.Position = 0;
                LoadComicInfo(ms);
            });
            archive.Entries.Where(e => e.FilePath.IsValidExtension()).ForEach(entry =>
            {
                Page page = Page.CreatePage(entry);
                pages.Add(page);
            });
            pages.Sort();
            Utility.Dispatcher.BeginInvoke(() => Pages.AddRange(pages));
        }

        protected override string Extension
        {
            get
            {
                return "cbr";
            }
        }

        protected override string Filter
        {
            get
            {
                return "CBR files (*.cbr)|*.cbr|All files (*.*)|*.*";
            }
        }
    }
}
